import { defineStore } from "pinia";
import { ref } from "vue";
import product from "./products.json"
import { ElMessage } from "element-plus";
export const store = defineStore("shoppingcar", {
    state: () => {
        return {
            productList: ref([]),
            shoppingCarList: ref([])
        }
    },
    actions: {
        getProductList() {
            this.productList = product
        },
        addToShoppingCar(item) {
            const res = this.productList.find(_item => {
                return _item.pid == item.pid
            })
            const _res = this.shoppingCarList.find(_item => {
                return _item.pid == item.pid
            })
            if (res.number >= 1) {
                if (!_res) {
                    this.shoppingCarList.push({
                        pid: item.pid,
                        photo: item.photo,
                        title: item.title,
                        price: item.price,
                        number: 1
                    })
                } else {
                    _res.number++
                }
                res.number--
                ElMessage.success({
                    message: "成功添加到购物车！"
                })
            } else {
                ElMessage.error({
                    message: "库存不足！"
                })
                return
            }

        },
        increment(id) {
            const res = this.productList.find(_item => {
                return _item.pid == id
            })
            const _res = this.shoppingCarList.find(_item => {
                return _item.pid == id
            })
            if (res.number == 0) {
                ElMessage.error({
                    message: "库存数量不足！"
                })
                return;
            }
            res.number--
            _res.number++
        },
        deincrement(id) {
            const res = this.productList.find(_item => {
                return _item.pid == id
            })
            const _res = this.shoppingCarList.find(_item => {
                return _item.pid == id
            })
            if (_res.number == 0) {
                ElMessage.error({
                    message: "您已经取消了本商品！"
                })
                // this.shoppingCarList = this.shoppingCarList.filter((_id,index,arr) => {
                //     return _id != id;
                // })
                return;
            }
            res.number++
            _res.number--
        },
        payoff(){
            ElMessage.success({
                message: "您已经成功支付了￥"+this.totalPrice+"元"
            })
            this.shoppingCarList=[]
        }
    },
    getters: {
        totalPrice() {
            var sum = this.shoppingCarList.reduce((prev, curr) => {
                prev += curr.price * curr.number
                return prev
            }, 0)
            return sum;
        }
    }

})